package reviewAlgorithms.dynamicProgramming;

public class CanPartition {
    public static void main(String[] args) {
        int[] nums = {1, 5, 11, 5};
        System.out.println(canPartition1(nums));
    }
    public static boolean canPartition(int[] nums) {
        if (nums == null || nums.length < 2) {
            return false;
        }
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
        }
        if (sum % 2 != 0){
            return false;
        }
        int target = sum/2;
        boolean[][] dp = new boolean[nums.length][target + 1];
        if (target > nums[0]){
            dp[0][nums[0]] = true;
        }
        for (int i = 1; i < nums.length; i++) {
            for (int j = 0; j < target + 1; j++) {
                if (j < nums[i]){
                    dp[i][j] = dp[i - 1][j];
                }else if (j > nums[i]){
                    dp[i][j] = dp[i - 1][j] || dp[i - 1][j - nums[i]];
                }else {
                    dp[i][j] = true;
                }
            }
            if (dp[i][target]){
                return true;
            }
        }
        return false;
    }
    public static boolean canPartition1(int[] nums) {
        int sum = computeArraySum(nums);
        if (sum % 2 != 0) {
            return false;
        }
        int W = sum / 2;
        boolean[] dp = new boolean[W + 1];
        dp[0] = true;
        for (int num : nums) { // 0-1 背包一个物品只能用一次
            for (int i = W; i >= num; i--) { // 从后往前，先计算 dp[i] 再计算 dp[i-num]
                dp[i] = dp[i] || dp[i - num];
            }
        }
        return dp[W];
    }
    private static int computeArraySum(int[] nums) {
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }
        return sum;
    }
}
